package map.android.baidu.carpool.reservation;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.baidu.components.api.extra.APIProxy;

import android.app.Activity;
import android.app.Dialog;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.utils.LogUtils;
import map.android.baidu.carpool.widget.wheel.OnWheelChangedListener;
import map.android.baidu.carpool.widget.wheel.WheelView;

public class CarPickUpTimeDialog extends Dialog {
	private Activity mActivity;
	public static final boolean VISIBLE = true;
	public static final boolean GONE = false;

	private WheelView hoursWheelView = null;
	private WheelView minsWheelView = null;
	private WheelView dayWheelView = null;

	private MinsWheelAdapter minAdapter = null;
	private HoursWheelAdapter hourAdapter = null;
	private DaysPickUpWheelAdapter dayAdapter = null;

	private ArrayList<Integer> mEmptyList = null;

	private OnSelectDateTimeListener dateTimeListener;
	private OnSelectNowListener todayListener;

	private boolean dayShow = true;
	private boolean hourShow = true;
	private boolean minShow = true;

	private static final double SCALE = 1.0;

	private Calendar mCalendarNow;
	private int mHourOfDay;
	private int mMinute;

	private int mMinuteData[] = { 0, 15, 30, 45 };
	private static final int MAX_MINUTE = 45;

	private static final int MAX_HOUR = 23;

	private static final int MAX_DAY = 60;

	private static final long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;

	private static final int BUFFER_MINUTE = 5;

	public interface OnSelectDateTimeListener {
		void dateTimeSelected(Calendar c);
	}

	public interface OnSelectNowListener {
		void selectNow();
	}

	public CarPickUpTimeDialog(Activity activity, OnSelectNowListener selectTodayListener,
			OnSelectDateTimeListener selectDateTimeListener, int style, boolean dayshow, boolean hourshow,
			boolean minshow) {
		super(activity, style);
		this.mActivity = activity;
		this.todayListener = selectTodayListener;
		this.dateTimeListener = selectDateTimeListener;
		this.dayShow = dayshow;
		this.hourShow = hourshow;
		this.minShow = minshow;

		init();
	}

	@SuppressWarnings("deprecation")
	private void init() {
		LayoutInflater inflater = APIProxy.res().getInflater();
		View view = inflater.inflate(R.layout.car_dialog_reservation_datetime_layout, null);

		setContentView(view);

		WindowManager windowManager = mActivity.getWindowManager();
		Display display = windowManager.getDefaultDisplay();

		Window window = getWindow();
		WindowManager.LayoutParams attributes = window.getAttributes();
		attributes.gravity = Gravity.BOTTOM;
		attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
		attributes.width = (int) (display.getWidth() * SCALE);
		window.setAttributes(attributes);

		initViewUseNew(view);
	}

	private void initViewUseNew(View view) {
		try {

			mEmptyList = new ArrayList<Integer>();
			mEmptyList.add(Integer.MAX_VALUE);

			LinearLayout wheelContainerView = (LinearLayout) view.findViewById(R.id.car_wheel_container);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			lp.weight = 0.33f;

			dayAdapter = new DaysPickUpWheelAdapter(mActivity);
			dayAdapter.setData(getDayList());

			dayWheelView = new WheelView(mActivity);
			wheelContainerView.addView(dayWheelView, lp);
			dayWheelView.setCurrentItem(0);
			dayWheelView.setViewAdapter(dayAdapter);
			dayWheelView.setVisibility(dayShow ? View.VISIBLE : View.GONE);

			dayAdapter.setItemResource(R.layout.car_wheel_text_item);
			dayAdapter.setItemTextResource(R.id.car_reservation_wheelview_text);
			dayWheelView.addChangingListener(new OnWheelChangedListener() {
				@Override
				public void onChanged(WheelView wheel, int oldValue, int newValue) {
					int currentHourItem = hoursWheelView.getCurrentItem();
					int item = wheel.getCurrentItem();
					Calendar c = dayAdapter.getItem(item);
					if (c == null) {
						hourAdapter.setData(mEmptyList);
					} else {
						hourAdapter.setData(getHourList(dayAdapter.getItem(item)));
					}

					if (currentHourItem >= hourAdapter.getItemsCount()) {
						hoursWheelView.setCurrentItem(hourAdapter.getItemsCount() - 1);
					}
					// hoursWheelView.setCurrentItem(0);
					mHoursWheelViewChangedlistener.onChanged(hoursWheelView, 0, 0);
				}
			});

			hoursWheelView = new WheelView(mActivity);
			wheelContainerView.addView(hoursWheelView, lp);

			hourAdapter = new HoursWheelAdapter(mActivity);
			//hourAdapter.setData(mEmptyList);
			hourAdapter.setData(getHourList(dayAdapter.getItem(0)));
			hoursWheelView.setCurrentItem(0);
			hourAdapter.setItemResource(R.layout.car_wheel_text_item);
			hourAdapter.setItemTextResource(R.id.car_reservation_wheelview_text);
			hoursWheelView.setViewAdapter(hourAdapter);
			hoursWheelView.setVisibility(hourShow ? View.VISIBLE : View.GONE);
			hoursWheelView.addChangingListener(mHoursWheelViewChangedlistener);

			minsWheelView = new WheelView(mActivity);
			wheelContainerView.addView(minsWheelView, lp);
			minsWheelView.setCurrentItem(0);

			minAdapter = new MinsWheelAdapter(mActivity);
			//minAdapter.setData(mEmptyList);
			minAdapter.setData(getMinuteList(dayAdapter.getItem(0), hourAdapter.getItemValue(hoursWheelView.getCurrentItem())));

			minAdapter.setItemResource(R.layout.car_wheel_text_item);
			minAdapter.setItemTextResource(R.id.car_reservation_wheelview_text);
			minsWheelView.setViewAdapter(minAdapter);
			minsWheelView.setVisibility(minShow ? View.VISIBLE : View.GONE);

			dayWheelView.setCurrentItem(0);

			TextView okTextView = (TextView) view.findViewById(R.id.car_reservation_wheel_ok_textview);
			okTextView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (dateTimeListener != null) {
						int dayCurrentItem = dayWheelView.getCurrentItem();
						Calendar calendar = dayAdapter.getItem(dayCurrentItem);
						if (calendar == null) {
							todayListener.selectNow();
						} else {

							int hour = hourAdapter.getItemValue(hoursWheelView.getCurrentItem());
							int min = minAdapter.getItemValue(minsWheelView.getCurrentItem());
							calendar.set(Calendar.HOUR_OF_DAY, hour);
							calendar.set(Calendar.MINUTE, min);
							dateTimeListener.dateTimeSelected(calendar);
						}
					}

					dismiss();
				}
			});

			TextView cancelTextView = (TextView) view.findViewById(R.id.car_reservation_wheel_cancel_textview);
			cancelTextView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dismiss();
				}
			});
		} catch (Exception e) {
			// TaxiUtils.logUseEngine(ERROR_LOGS.ARR_PRICE_CAST_ERROR);
			e.printStackTrace();
		}
	}

	OnWheelChangedListener mHoursWheelViewChangedlistener = new OnWheelChangedListener() {
		@Override
		public void onChanged(WheelView wheel, int oldValue, int newValue) {
			int currentMinute = minsWheelView.getCurrentItem();
			Calendar c = dayAdapter.getItem(dayWheelView.getCurrentItem());
			if (c == null) {
				minAdapter.setData(mEmptyList);
			} else {
				minAdapter.setData(getMinuteList(c, hourAdapter.getItemValue(hoursWheelView.getCurrentItem())));
			}
			if (currentMinute >= minAdapter.getItemsCount()) {
				minsWheelView.setCurrentItem(minAdapter.getItemsCount() - 1);
			}
		}
	};

	List<Calendar> getDayList() {
		List<Calendar> list = new ArrayList<Calendar>();
		//list.add(null);
		mCalendarNow = Calendar.getInstance(Locale.CHINESE);
		mHourOfDay = mCalendarNow.get(Calendar.HOUR_OF_DAY);
		mMinute = mCalendarNow.get(Calendar.MINUTE);
		// 如果现在的时间是在23:00之前，并且不是在22:40分之后，那么今天是可选的，将今天加入list中
		if (mHourOfDay < MAX_HOUR && !(mHourOfDay == MAX_HOUR - 1 && mMinute >= MAX_MINUTE - BUFFER_MINUTE)) {
			LogUtils.d("chenlei18", "时间控件 ---------- 走这里");
			list.add(mCalendarNow);
		    dayAdapter.setmTodayStatus(true);
		}else{
			LogUtils.d("chenlei18", "时间控件 ---------no- bu走这里");
		}
		Calendar today = mCalendarNow;

		// 将往后的60天都加入list中
		for (int i = 0; i < MAX_DAY; i++) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(today.getTimeInMillis() + DAY_IN_MILLISECONDS);
			today = calendar;
			list.add(today);
		}
		return list;
	}

	List<Integer> getHourList(Calendar calendar) {
		List<Integer> list = new ArrayList<Integer>();
		if (isToday(calendar)) {// 如果是今天
			// 将今天之后的小时都加入list中
			for (int i = mHourOfDay + 1; i < 24; i++) {
				list.add(i);
			}
			// 如果现在的时间是在40分以后，那么下一个小时是不可选的，将下一个小时去掉
			if (mMinute > MAX_MINUTE - BUFFER_MINUTE) {
				list.remove(0);
			}
		} else {
			for (int i = 0; i < 24; i++) {
				list.add(i);
			}
			// 如果选的是明天，并且现在时间是23:40分以后，那么将0点去掉
			if (mHourOfDay == MAX_HOUR && mMinute > MAX_MINUTE - BUFFER_MINUTE && isTomorrow(calendar)) {
				list.remove(0);
			}
		}
		return list;
	}

	List<Integer> getMinuteList(Calendar calendar, int hourSelected) {
		List<Integer> list = new ArrayList<Integer>();

		if ((hourSelected == mHourOfDay + 1) && isToday(calendar)
				|| (mHourOfDay == MAX_HOUR && hourSelected == 0 && isTomorrow(calendar))) {
			// 如果选的时间是现在时间的下一个小时内，也就是（今天的小时加一）或者是（现在23点，选了明天0点）
			for (int i = 0; i < mMinuteData.length; i++) {
				// 将现在分钟+buffer时间往后的分钟都加入list中，保证间隔在65分钟以上
				if (mMinuteData[i] > mMinute + BUFFER_MINUTE) {
					list.add(mMinuteData[i]);
				}
			}
		} else if ((isToday(calendar) && mMinute >= 60 - BUFFER_MINUTE && hourSelected == mHourOfDay + 2)
				|| (isTomorrow(calendar) && mMinute >= 60 - BUFFER_MINUTE
						&& (mHourOfDay == MAX_HOUR || mHourOfDay == MAX_HOUR - 1) && hourSelected == (mHourOfDay + 2) % 24)) {
			// 如果选的时间是现在时间的往后第二个小时，并且现在分钟是在55分以后，那么第二个小时的整点是不能选的，只能从15分开始选
			for (int i = 1; i < mMinuteData.length; i++) {
				list.add(mMinuteData[i]);
			}
		} else {
			// 否则所有分钟都是可选的
			for (int i = 0; i < mMinuteData.length; i++) {
				list.add(mMinuteData[i]);
			}

		}
		return list;
	}

	boolean isToday(Calendar calendar) {
		return mCalendarNow.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)
				&& mCalendarNow.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)
				&& mCalendarNow.get(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH);
	}

	boolean isTomorrow(Calendar calendar) {

		return calendar.after(mCalendarNow)
				&& calendar.getTimeInMillis() - mCalendarNow.getTimeInMillis() == DAY_IN_MILLISECONDS;
	}

}
